<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
          v-model="selectedCateKeys"
          :options="catelist"
          :props="{ expandTrigger: 'hover' , value: 'cat_id',  label: 'cat_name', children:'children'}"
          @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- Tab区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled='isBtnDisabled' @click="addDialogVisible=true">添加参数</el-button>
          <!-- 表格区域 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="index" v-for="(item, index) in scope.row.attr_vals" closable @close="closeTag(scope.row,index)">{{item}}</el-tag>
                <!-- 添加小Tag -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域操作接收数据 -->
              <template slot-scope="scope">
              <el-button type="primary" size="mini" @click=" modifyData(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteData(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled='isBtnDisabled' @click="addDialogVisible=true">添加属性</el-button>
           <!-- 表格区域 -->
           <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
               <template slot-scope="scope">
                <el-tag :key="index" v-for="(item, index) in scope.row.attr_vals" closable @close="closeTag(scope.row,index)">{{item}}</el-tag>
                <!-- 添加小Tag -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域操作接收数据 -->
              <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="modifyData(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteData(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数窗口弹出层 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" @close="addDialogClose()" width="30%">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改按钮-窗口弹出层 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="modifyDialogVisible" @close="modifyDialogClose()" width="30%">
      <el-form :model="modifyForm" :rules="rules" ref="modifyFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="modifyForm.attr_name"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyDataSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除按钮-窗口弹出层 -->
    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="30%" >
      <span><i class="el-icon-delete red"></i>  此操作将永久删除该参数, 是否继续?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类数据列表
      catelist: [],
      // 级联选择框配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框 被选中的数据的id组成的数组
      selectedCateKeys: [],
      // 被激活的页签名称
      activeName: 'many',
      // 动态和静态的参数存储列表
      manyTableData: [],
      onlyTableData: [],
      // 是否显示添加的弹出框
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加参数表单的验证规则
      rules: {
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      // 修改数据
      modifyDialogVisible: false,
      modifyForm: {
        attr_name: ''
      },
      // 删除数据
      deleteDialogVisible: false,
      // 小Tag
      tagData: []
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 1、获取所有商品分类数据列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据列表失败')
      // console.log(res.data)
      this.catelist = res.data
    },
    // 2、获取参数列表数据
    async getParamsData () {
      // 只能选中三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 选中的是三级分类就打印出来
      console.log('被选中id：' + this.selectedCateKeys)
      // 根据所选分类的id 和 当前所在tab页 调用接口获取数据
      const { data: res } = await this.$http.get('categories/' + this.cateid + '/attributes', { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制小Tag的显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
        this.tagData.push(item.attr_vals)
      })
      // 判断获取的数据是静态数据还是动态的
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    handleChange () {
      this.getParamsData()
    },
    // 切换Tab页触发
    handleTabClick () {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 关闭添加属性对话框，重置表单
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 3、点击确定按钮，添加属性，调用接口
    addParams () {
      // 如果表单通过验证就继续
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // console.log(this.selectedCateKeys[2]) 这是当前被选中的id值
          const path = 'categories/' + this.selectedCateKeys[2] + '/attributes'
          const params = {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
          const { data: res } = await this.$http.post(path, params)
          if (res.meta.status !== 201) return this.$message.error('创建失败')
          this.getParamsData()
          this.addDialogVisible = false
          this.$message.success('创建成功')
        }
      })
    },
    // 4、点击编辑修改按钮
    async modifyData (formData) {
      // console.log(formData)
      this.modifyForm = formData
      this.modifyDialogVisible = true
    },
    // 重置修改窗口表单
    modifyDialogClose () {
      this.$refs.modifyFormRef.resetFields()
    },
    // 点击确定按钮，修改属性，调用接口
    modifyDataSubmit () {
      this.$refs.modifyFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('categories/' + this.modifyForm.cat_id + '/attributes/' + this.modifyForm.attr_id, {
          attr_name: this.modifyForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getParamsData()
        this.modifyDialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 5、点击删除按钮
    deleteData (formData) {
      this.modifyForm = formData
      this.deleteDialogVisible = true
    },
    // 点击确定，调用接口，删除此条数据
    async deleteSubmit () {
      const { data: res } = await this.$http.delete('categories/' + this.modifyForm.cat_id + '/attributes/' + this.modifyForm.attr_id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getParamsData()
      this.deleteDialogVisible = false
      this.$message.success('删除成功')
    },
    // 6、点击删除小Tag标签，调用接口
    async saveAttrVals (row) {
      // 此函数用来将tag的修改保存到数据库中
      // 调用接口，保存操作
      const { data: res } = await this.$http.put('categories/' + this.cateid + '/attributes/' + row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('修改成功')
    },
    closeTag (data, tagkey) {
      data.attr_vals.splice(tagkey, 1)
      this.saveAttrVals(data)
    },
    // 添加一个小Tag
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      // 不为0，就是输入了内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    showInput (data) {
      data.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }

  },
  // 计算属性
  computed: {
    // 按钮是否需要被禁用
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 被选择的三级分类的id
    cateid () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 是添加参数还是添加属性
    titleText () {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-tag {
  margin: 5px;
}

.input-new-tag {
  width: 100px
}
</style>
